package com.dunke.web.handler;

import com.dunke.core.common.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 参数异常统一处理
 */
@RestControllerAdvice
public class BadRequestExceptionHandler {


    /**
     * 处理不带任何注解的参数绑定校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public Result handleBingException(BindException e) {
        String errorMsg = e.getBindingResult().getAllErrors()
                .stream()
                .map(objectError -> ((FieldError)objectError).getField() + ((FieldError)objectError).getDefaultMessage())
                .collect(Collectors.joining(","));
        //"errorMsg": "name不能为空,age最小不能小于18"
        return Result.error(errorMsg);
    }

    /**
     * JSON方式：校验失败后，会抛出一个 MethodArgumentNotValidException
     * 处理 @RequestBody参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String errorMsg = e.getBindingResult().getAllErrors()
                .stream()
                .map(objectError -> ((FieldError)objectError).getField() + ((FieldError)objectError).getDefaultMessage())
                .collect(Collectors.joining(","));

//        "errorMsg": "name不能为空,age最小不能小于18"
//        StringBuilder sb = new StringBuilder();
//        e.getBindingResult().getAllErrors().forEach(error -> {
//            String fieldName = ((FieldError) error).getField();
//            sb.append("[").append(fieldName).append("]")
//                    .append(error.getDefaultMessage()).append(";    ");
//        });
        return Result.error(errorMsg);
    }

    /**
     * 表单方式：校验失败，会抛出一个ConstraintViolationException
     * @param cve
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result methodArgNotValidException(ConstraintViolationException cve) {

        String errorMsg = cve.getConstraintViolations().stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining());
//        Set<ConstraintViolation<?>> cves = cve.getConstraintViolations();
//        StringBuffer errorMsg = new StringBuffer();
//        cves.forEach(ex -> errorMsg.append(ex.getMessage()));
        return Result.error(errorMsg);
    }
}

